package com.eunion.web.cms.entity.spec;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.eunion.web.cms.entity.University;

public final class UniversitySpec {


	public static Specification<University> build(University queryBean) {
		return new UniversityQuery(queryBean);
	}

	public static Specification<University> build(University queryBean,boolean accurate) {
		return new UniversityQuery(queryBean,accurate);
	}

	private static class UniversityQuery implements Specification<University> {

		private boolean accurate = false;
		private University queryBean;

		private UniversityQuery(University queryBean) {
			this.queryBean = queryBean;
		}

		private UniversityQuery(University queryBean,boolean accurate) {
			this.queryBean = queryBean;
			this.accurate = accurate;
		}

		@Override
		public Predicate toPredicate(Root<University> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			List<Predicate> list = getPredicates(root, query, cb, queryBean,accurate);
			Predicate[] preList = new Predicate[list.size()];
			if(accurate) {
				return cb.or(list.toArray(preList));
			} else {
				return cb.and(list.toArray(preList));
			}
			
		}

	}

	private static List<Predicate> getPredicates(Root<University> root, CriteriaQuery<?> query, CriteriaBuilder cb,
			University queryBean,boolean accurate) {
		// 条件集合
		List<Predicate> list = new ArrayList<>();
		// 学校代码条件
		String code = queryBean.getCode();
		// 学校名称条件
		String name = queryBean.getName();
		// 大学层级条件（本科、专科）
		String level = queryBean.getLevel();
		if(accurate) {
			if (StringUtils.isNotBlank(code) ) {
				list.add(cb.equal(root.get("code"), code.trim()));
			} 
			if(StringUtils.isNotBlank(name)) {
				list.add(cb.equal(root.get("name"), name.trim()));
			}
		} else {
			if (StringUtils.isNotBlank(code)) {
				list.add(cb.equal(root.get("code"), code.trim()));
			} else {
				// code不能为空
				String str = "";
				list.add(cb.notEqual(root.get("code"), str));
			}

			if (StringUtils.isNotBlank(name)) {
				list.add(cb.like(root.get("name"), "%" + name.trim() + "%"));
			}
			if (StringUtils.isNotBlank(level)) {
				list.add(cb.equal(root.get("level"), level.trim()));
			}
		}

		return list;
	}
}
